class ProgressStore {
  constructor() {
    this.tasks = new Map()
    this.cleanupInterval = setInterval(() => {
      this.cleanupExpiredTasks()
    }, 60 * 1000)
  }

  // 创建新任务
  createTask(taskId, totalFiles, totalSize) {
    this.tasks.set(taskId, {
      progress: 0,
      status: 'pending',
      totalFiles,
      processedFiles: 0,
      totalSize,
      processedSize: 0,
      createdAt: Date.now(),
      updatedAt: Date.now(),
      isCancelled: false
    })
    return taskId
  }

  // 更新任务进度
  updateProgress(taskId, processedFiles, processedSize) {
    const task = this.tasks.get(taskId)
    if (task && !task.isCancelled) {
      task.processedFiles = processedFiles
      task.processedSize = processedSize
      task.progress = Math.min(
        Math.round((processedSize / task.totalSize) * 100),
        100
      )
      task.updatedAt = Date.now()
      
      if (task.progress >= 100) {
        task.status = 'completed'
      }
    }
  }

  // 取消任务
  cancelTask(taskId) {
    const task = this.tasks.get(taskId)
    if (task) {
      task.isCancelled = true
      task.status = 'cancelled'
      task.updatedAt = Date.now()
      return true
    }
    return false
  }

  // 获取任务进度
  getProgress(taskId) {
    const task = this.tasks.get(taskId)
    if (!task) return null
    
    return {
      progress: task.progress,
      status: task.status,
      totalFiles: task.totalFiles,
      processedFiles: task.processedFiles,
      totalSize: task.totalSize,
      processedSize: task.processedSize,
      speed: this.calculateSpeed(taskId),
      updatedAt: task.updatedAt
    }
  }

  // 计算处理速度 (字节/秒)
  calculateSpeed(taskId) {
    const task = this.tasks.get(taskId)
    if (!task || task.processedSize === 0) return 0
    
    const timeElapsed = (Date.now() - task.createdAt) / 1000 // 秒
    return Math.round(task.processedSize / timeElapsed)
  }

  // 清理过期任务
  cleanupExpiredTasks() {
    const now = Date.now()
    for (const [taskId, task] of this.tasks.entries()) {
      if (now - task.updatedAt > 3600 * 1000) { // 1小时
        this.tasks.delete(taskId)
      }
    }
  }
}

module.exports = new ProgressStore()